<?php
/**
 * @author SHIH
 * @date 2020/10/14 10:06
 */

namespace app\utils;

use JsonSerializable;

/**
 * 返回结果封装
 * Class Result
 * @package app\utils
 */
class Result implements JsonSerializable {

    private $code;
    private $msg;
    private $data;

    /**
     * Result constructor.
     * @param int    $code
     * @param string $msg
     * @param string $data
     */
    public function __construct($code = 0, $msg = "success", $data = "") {
        $this->code = $code;
        $this->msg = $msg;
        $this->data = $data;
    }

    /**
     * 成功返回结果
     * @param string $data 返回数据
     * @return Result
     * @author SHIH
     * @date 2020/10/14 10:36
     */
    public static function ok($data = "") {
        return new self(0, "success", $data);
    }

    /**
     * 失败返回结果
     * @param array  $businessStatus BusinessStatus枚举值
     * @param string $data 返回数据
     * @return Result
     * @author SHIH
     * @date 2020/10/14 10:34
     */
    public static function fail($businessStatus, $data = "") {
        return new self($businessStatus[0], $businessStatus[1], $data);
    }

    public function __toString() {
        return json_encode($this);
    }

    /**
     * @return int
     */
    public function getCode() {
        return $this->code;
    }

    /**
     * @param int $code
     */
    public function setCode($code) {
        $this->code = $code;
    }

    /**
     * @return string
     */
    public function getMsg() {
        return $this->msg;
    }

    /**
     * @param string $msg
     */
    public function setMsg($msg) {
        $this->msg = $msg;
    }

    /**
     * @return string
     */
    public function getData() {
        return $this->data;
    }

    /**
     * @param string $data
     */
    public function setData($data) {
        $this->data = $data;
    }

    /**
     * 重写jsonSerialize
     * @return array|mixed
     * @author SHIH
     * @date 2020/11/21 9:58
     */
    public function jsonSerialize() {
        return [
            "code" => $this->getCode(),
            "msg"  => $this->getMsg(),
            "data" => $this->getData(),
        ];
    }
}